package com.lnlyj.media.data.load;

import android.content.ContentResolver;
import android.database.Cursor;
import android.os.AsyncTask;
import android.util.Log;

import com.lnlyj.media.data.MediaGroup;
import com.lnlyj.media.data.MediaItem;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * wanglei 2020-04-16
 */
public class MediaLoader extends AsyncTask<Void, Void, Void> {

    public static final String TAG = "MediaLoader";

    private OnMediaLoaderCallback callback;
    private ContentResolver resolver;
    private QueryConfig config;

    public MediaLoader(ContentResolver resolver, QueryConfig config) {
        this.resolver = resolver;
        this.config = config;
    }

    @Override
    protected Void doInBackground(Void... voids) {

        Cursor cursor = null;
        try {
            List<MediaGroup> list = new ArrayList<>();

            cursor = resolver.query(config.uri, config.projection, config.selection, config.selectionArgs, config.sortOrder);

            DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

            MediaGroup group = new MediaGroup();

            while (cursor.moveToNext()) {
                long t1 = cursor.getLong(cursor.getColumnIndex("date_modified"));
                String d1 = dateFormat.format(t1 * 1000);
//                MediaGroup group = getTimeLineGroup(list, d1, t1);
                group.items.add(newMediaData(cursor));
            }
            list.add(group);

            if (callback != null) {
                callback.onLoaderFinish(list);
            }
        } catch (Exception e) {
            Log.w(TAG, e.getMessage());
        } finally {
            if (cursor != null) {
                cursor.close();
                cursor = null;
            }
        }

        return null;
    }

    private MediaItem newMediaData(Cursor cursor) {
        MediaItem item = new MediaItem(cursor);
        item.setTitle(false);
        return item;
    }

    private MediaGroup getTimeLineGroup(List<MediaGroup> groups, String time, long modified) {
        MediaGroup group = null;

        for (MediaGroup g : groups) {
            if (g.time.equals(time)) {
                return g;
            }
        }

        group = new MediaGroup();
        group.time = time;
        group.dateModified = modified;

        groups.add(group);

        return group;
    }

    public void setCallback(OnMediaLoaderCallback callback) {
        this.callback = callback;
    }

    public interface OnMediaLoaderCallback {
        void onLoaderFinish(List<MediaGroup> list);
    }

}
